package com.maple.phoneward.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

import com.maple.phoneward.constants.Constants;
import com.maple.phoneward.service.LockedService;
import com.maple.phoneward.service.SimService;
import com.maple.phoneward.service.SystemService;
import com.maple.phoneward.utils.AppUtil;
import com.maple.phoneward.utils.CmdUtil;
import com.maple.phoneward.utils.Logger;
import com.maple.phoneward.utils.StringUtil;

/**
 * AppBroadcastReceiver.java
 * 
 * @author YaJian Qiu
 * @time 2013-3-30 上午9:39:17<br>
 *       本类描述：广播接收器
 * 
 */
public class AppBroadcastReceiver extends BroadcastReceiver {

	public static final String BOOT_ACTION = "android.intent.action.BOOT_COMPLETED"; // 开机Action
	public static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED"; // 短信接收Action
	public static final String TAG = "AppBroadcastReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (StringUtil.equals(BOOT_ACTION, action)) {
			Logger.d(TAG, "接收到开机广播");
			// 启动系统服务
			Intent service = new Intent(context, SystemService.class);
			context.startService(service);
			Intent simService = new Intent(context, SimService.class);
			context.startService(simService);
			
			boolean isLockModel = AppUtil.getFromSharedPreferences(context, Constants.IS_LOCK_MODEL, Boolean.class);
			if(isLockModel){
				Intent s = new Intent(context, LockedService.class);
				context.startService(s);
			}
			
		} else if (StringUtil.equals(SMS_ACTION, action)) {
			Logger.d(TAG, "接收到短信广播");
			Boolean isServiceOpen = AppUtil.getFromSharedPreferences(context, Constants.IS_SERVICE_OPEN,Boolean.class);
			if(!isServiceOpen){
				Logger.d(TAG, "防盗保护未开启");
				return;
			}
			Bundle bundle = intent.getExtras();
			Object messages[] = (Object[]) bundle.get("pdus");
			SmsMessage smsMessage[] = new SmsMessage[messages.length];

			// 截取短信内容
			for (int n = 0; n < messages.length; n++) {
				smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
				String sender = smsMessage[n].getOriginatingAddress();// 发送号码
				String body = smsMessage[n].getMessageBody();
				CmdUtil cmdUtil = new CmdUtil(context);
				if (cmdUtil.isCmd(body)) {
					this.abortBroadcast();// 如果是防盗指令，则终止广播
					cmdUtil.executeCmd(sender, body);
					Logger.d(TAG, "接收到指令短信:"+body + "  发送号码："+sender);
				}
			}

		}

	}

}
